/*
 * @FileName: [UserController.java]
 * 
 * @Package controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 3589 $ $LastChangedDate: 2013-10-12 10:19:36 +0800 (周六, 2013-10-12) $ $LastChangedBy: huangb $
 * 
 * @category bcinfo
 * 
 * @version 1.1
 * 
 * @author $Author: huangb $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bci.pwtz.controller.admin;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bci.pwtz.admin.service.AdminSmsSendLogService;
import com.bci.pwtz.admin.service.AdminUserService;
import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.CookieUtil;
import com.bci.pwtz.common.util.ExcelUtil;
import com.bci.pwtz.common.util.JsonUtils;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.common.util.SHA256Cryptor;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.exception.VerifyCodeIsBusyException;
import com.bci.pwtz.exception.VisitCountIsOverTheLimitException;
import com.bci.pwtz.mysql.model.AdminSmsSendLog;
import com.bci.pwtz.mysql.model.AdminUser;
import com.bci.pwtz.mysql.model.SmsSendLog;
import com.bci.pwtz.service.VerifyCodeService;
import com.bci.pwtz.service.sms.SendSmsService;



/**
 * 用户控制器controller <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能 <br/>
 * 登陆 <br/>
 * 
 * <PRE>
 *      /user/${actionName}
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/admin/adminuser")
public class AdminUserController extends AdminAbstractController
{
    @Autowired
    private AdminUserService     adminUserService;
    @Autowired
    private VerifyCodeService     verifyCodeService;
    @Autowired
    private SendSmsService     sendSmsService;
    @Autowired
    private AdminSmsSendLogService     smsSendLogService;
   
    /**
     * 
     * 执行登录操作(异步请求) <br/>
     * <p>
     * Description: 执行登录操作,登录成功后记录用户信息到session <br/>
     * <p>
     * Author: huangb<br/>
     * <p>
     * Date: 2014-9-12-下午4:09:11<br/>
     * <p>
     * 
     * @param session
     * @param loginName
     * @param pwd
     * @param imageCode
     * @return
     * 
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> login(HttpServletRequest req,HttpServletResponse resp,String loginName, String pwd, String imageCode,String status)
    {
        String imageCodeSession = (String) session.getAttribute("imageCode");
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            if ((StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode)))
            {
                pwd = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY+pwd);
                System.out.println("login: loginName="+loginName+"|pwd="+pwd);
                AdminUser user = adminUserService.findUserInfo(loginName,pwd);
                if (null != user)
                {
                    Long userId = user.getAdminUserId();
                    session.setAttribute("adminuser", user);
                    session.setAttribute("adminuserId", userId);
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,
                            "登录成功");
                    setLog(1, "用户【"+loginName+"】登录成功", getUserId());
                    if("1".equals(status)){
                        CookieUtil.rocordAccountCookie(req,resp,loginName,pwd);
                    }
                }
                else
                {
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                            "VisitInvalidParametersException", "登录名不存在或密码错误！");
                }
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "ErrorImageCode", "验证码错误！");
            }
        }
        catch (PwtzException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        session.removeAttribute("imageCode");

        return respMap;
    }
    /**
     * 执行登出操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:10:46<br/>
     * <p>
     * @param userId
     * @return   
     *
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public void logout(HttpServletRequest req,HttpServletResponse resp,String loginUrl)
    {
        if(session.getAttribute("adminuserId")!=null)
        {
            AdminUser user= (AdminUser)session.getAttribute("adminuser");
            if(user!=null){
                setLog(1, "用户【"+user.getLoginName()+"】注销成功", getUserId());
            }
            session.removeAttribute("adminuserId");
            session.removeAttribute("adminuser");
            CookieUtil.removeAccountCookie(req,resp);
            
        }
        try
        {
            resp.sendRedirect(loginUrl+"?t="+System.currentTimeMillis());
            
        }
        catch (IOException e)
        { }
    }
    /**
     * 执行获取短信验证码操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:11:05<br/>
     * <p>
     * @param mobile
     * @param type
     * @return   
     *
     */
    /*@RequestMapping(value = "/getcode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> getCode(String mobile,int type)
    {
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            int ret=adminUserService.selectCountByMobile(mobile);
            if(type==1){
                if(ret>0){
                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号码已注册");
                    return respMap;
                }
            }
            if(type==2){
                if(ret==0){
                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号码不存在");
                    return respMap;
                }
            }
            String code = verifyCodeService.getCode(mobile,type);
            if(code!=null){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"获取验证码成功");
                String msg = MessageFormat.format(PwtzConstants.GET_SWITCH_TEL_CODE_MSG, code);
                String[] mobiles=new String[]{mobile};
                sendSmsService.batchSend(mobiles, msg, null, null);
            }else{
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"获取验证码失败");
            }
        }
        catch (NumberFormatException e)
        {
            respMap=packageException(e);
        }
        catch (PwtzDatabaseException e)
        {
            respMap=packageUppException(e);
        }
        catch (VerifyCodeIsBusyException e)
        {
            respMap=packageException(e);
        }
        catch (VisitCountIsOverTheLimitException e)
        {
            respMap=packageException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (PwtzException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return respMap;
    }*/
    
    @RequestMapping(value = "/modifypassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> modifyPassword(String oldpassword,String password)
    {
    	Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            if(StringUtils.isEmpty(oldpassword) ||StringUtils.isEmpty(password)){
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
                return respMap;
            }
            long adminUserId = (Long)session.getAttribute("adminuserId");
            //String adminUserId = "1";
            oldpassword = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + oldpassword);
            //System.out.println("oldpassword="+oldpassword);
            int res = adminUserService.selectCountByPassword(adminUserId, oldpassword);
            if (res == 0){
            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "旧密码输入不正确");
                return respMap;
            }
            AdminUser adminUser = new AdminUser();
            adminUser.setAdminUserId(Long.valueOf(adminUserId));
            adminUser.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password));
            int result = adminUserService.update(adminUser);
            if (result>0)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"密码修改成功");
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "密码修改失败");
            }

        }
        catch (PwtzDatabaseException e)
        {
        	respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageException(e);
        }
        return respMap;
    }
    
    /*@RequestMapping(value = "/forgetpassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> forgetPassword(String mobile,String code,String imageCode)
    {
    	String imageCodeSession = (String) session.getAttribute("imageCode");
    	Map<String, String> respMap = new HashMap<String, String>();
        try
        {
        	if ((StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode))){
	            if(StringUtils.isEmpty(mobile) ||StringUtils.isEmpty(code) ||StringUtils.isEmpty(imageCode)){
	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
	                return respMap;
	            }
	            int isMobile = adminUserService.selectCountByMobile(mobile);
	            if (isMobile == 0){
	            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "电话号码不存在");
	                return respMap;
	            }
	            int res = verifyCodeService.validateCode(mobile, code);
	            if (res == 0){
	            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机验证码错误！");
	                return respMap;
	            }
	            //String adminUserId = (String)session.getAttribute("userId");
	            //String adminUserId = "2";
	            String newPassword = PwtzConstants.PASSWORD_KEY + PwtzUtils.getRandomNumber(6);
	            //System.out.println("newPassword="+newPassword);
	            //AdminUser adminUser = new AdminUser();
	            //adminUser.setAdminUserId(Long.valueOf(adminUserId));
	            //adminUser.setLoginPwd(SHA256Cryptor.sha256Encrypt(newPassword));
	            int result = adminUserService.updatePwdByMobile(SHA256Cryptor.sha256Encrypt(newPassword), mobile);
	            if (result>0)
	            {
	                newPassword=newPassword.substring(PwtzConstants.PASSWORD_KEY.length());
	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"密码修改成功");
	                String msg = MessageFormat.format(PwtzConstants.MODIFIED_PASSWORD_MSG, newPassword);
	                String smsReturn = sendSmsService.batchSend(mobile.split(","), msg, null, null);
	                if("0".equals(smsReturn) || "1".equals(smsReturn)){
	                	AdminSmsSendLog smsSendLog = new AdminSmsSendLog();
	                	smsSendLog.setMobile(mobile);
	                	smsSendLog.setContent(msg);
	                	smsSendLog.setOperatorId(getUserId());
	                	smsSendLogService.add(smsSendLog);
	                }
	            }
	            else
	            {
	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "密码修改失败");
	            }
        	}else{
        		respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorImageCode", "验证码错误！");
        	}

        }
        catch (PwtzDatabaseException e)
        {
        	respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageException(e);
        }
        return respMap;
    }*/
    
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> edit(String userName)
    {
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            if(userName.length()>10){
                return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "VisitInvalidParametersException", "名称超长！");
            }
            Long userId = (Long)session.getAttribute("userId");

            AdminUser user = adminUserService.load(userId);
            if (null != user)
            {
                user.setUserName(userName);
                int ret =adminUserService.update(user);
                if(ret>0){
                    session.setAttribute("adminuser", user);
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,
                        "修改用户信息成功");
                }else{
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                            "VisitInvalidParametersException", "修改用户信息失败！");
                }
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "VisitInvalidParametersException", "用户不存在！");
            }
        }
        catch (PwtzException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
  //用户名是否已被注册
        @RequestMapping(value = "/getLoginNameCount", method = RequestMethod.POST)
        @ResponseBody
        public Map<String, String> getLoginNameCount(String loginName)
        {
            Map<String, String> respMap = new HashMap<String, String>();
            try
            {
                int count = adminUserService.selectCountByName(loginName);
                respMap.put(ERROR_KEY_OP_RESULT, ERROR_VALUE_OP_RESULT_SUCCESS);
                respMap.put("count", String.valueOf(count));    
            }
            catch (PwtzDatabaseException e)
            {
                respMap = packageUppException(e);
            }
            catch (Exception e)
            {
                respMap = packageException(e);
            }
            return respMap;
        }
      //手机号是否已被注册
        @RequestMapping(value = "/getMobileCount", method = RequestMethod.POST)
        @ResponseBody
        public Map<String, String> getMobileCount(String mobile)
        {
            Map<String, String> respMap = new HashMap<String, String>();
            try
            {
                int count = adminUserService.selectCountByMobile(mobile);  
                respMap.put(ERROR_KEY_OP_RESULT, ERROR_VALUE_OP_RESULT_SUCCESS);
                respMap.put("count", String.valueOf(count));    
            }
            catch (PwtzDatabaseException e)
            {
                respMap = packageUppException(e);
            }
            catch (Exception e)
            {
                respMap = packageException(e);
            }
            return respMap;
        }
    @RequestMapping(value = "/changemobile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> changeMobile(String password,String mobile,String code)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        try
        {
                if(StringUtils.isEmpty(mobile) ||StringUtils.isEmpty(code) || StringUtils.isEmpty(password)){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
                    return respMap;
                }
                int isMobile = adminUserService.selectCountByMobile(mobile);
                if (isMobile > 0){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "电话号码已存在");
                    return respMap;
                }
                int res = verifyCodeService.validateCode(mobile, code);
                if (res == 0){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机验证码错误");
                    return respMap;
                }
                long adminUserId = (Long)session.getAttribute("userId");
                
                password = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password);
                int ret = adminUserService.selectCountByPassword(adminUserId,password);
                if (res > 0){
                    AdminUser user = adminUserService.load(adminUserId);
                    user.setAdminUserId(adminUserId);
                    user.setMobile(mobile);
                    ret = adminUserService.update(user);
                    if(ret>0){
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"手机号码变更成功");
                        session.setAttribute("adminuser", user);
                    }else{
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机号码变更失败");
                    }
                }else{
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "原密码错误");
                }

        }
        catch (PwtzDatabaseException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> add(String loginName,String mobile,String userName){
        Map<String, String> respMap = new HashMap<String, String>(2);
        try{
            AdminUser adminUser = (AdminUser)session.getAttribute("adminuser");
            if(StringUtils.isEmpty(loginName)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"登录名为空");
                return respMap;
            }
            if(!PwtzUtils.isName(loginName)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"用户名必须为6-20位字母或数字");
                return respMap;
            }
            if(StringUtils.isEmpty(mobile)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码为空");
                return respMap;
            }
            if(!PwtzUtils.isMobile(mobile)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码错误");
                return respMap;
            }
            int ret=adminUserService.selectCountByName(loginName);
            if(ret>0){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"用户名已被注册");
                return respMap;
            }
            ret=adminUserService.selectCountByMobile(mobile);
            if(ret>0){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号已被注册");
                return respMap;
            }
            AdminUser cuser=new AdminUser();
            cuser.setLoginName(loginName);
            cuser.setMobile(mobile);
            cuser.setUserName(userName);
            String password = PwtzUtils.getRandomNumber(6);
            cuser.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password));

            cuser = adminUserService.add(cuser);
            if (cuser!=null)
            {
                Long userId = cuser.getAdminUserId();
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"添加用户成功");
                String smsReturn = sendSmsService.batchSend(mobile.split(","), "用户名为:"+loginName+"密码为："+password, null, null);
                if("0".equals(smsReturn) || "1".equals(smsReturn)){
                	AdminSmsSendLog smsSendLog = new AdminSmsSendLog();
                    smsSendLog.setMobile(mobile);
                    smsSendLog.setContent("密码为："+password);
                    smsSendLog.setOperatorId(getUserId());
                    smsSendLogService.add(smsSendLog);
                }
               setLog(1, "新增【"+loginName+"】成功", getUserId());
            }else{
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"添加用户失败");
            }
        }catch(Exception e){
            respMap=packageException(e);
        }
        return respMap;
    }
    
    
    /**
     * 
     * 文件上传，读取号码文件入库(异步调用) <br/>
     * <p>
     * Description: 文件上传，读取号码文件入库(详细描述) <br/>
     * <p>
     * Author: huangb<br/>
     * <p>
     * Date: 2013-7-3-上午9:12:00<br/>
     * <p>
     * 
     * @param test
     * @param multipartRequest
     * @return
     * 
     */
    @RequestMapping("/readfile")
    @ResponseBody
    public void readFile(HttpServletRequest request,HttpServletResponse response,MultipartFile userFile)
    {
        List<String[]> errorlist =new ArrayList<String[]>();
        System.out.println("userFile="+userFile);
        String result = "";
//        List<String> errorlist = new ArrayList<String>();
        int totalCount = 0;
        int successCount = 0;
        int eroorCount = 0;
        String errorCardNums = "";
        String msgType = "error";
        String opResult = "1";
        String url = "";
        String savePath = "";
        if(PwtzConstants.THE_SERVER_TYPE==1){
            savePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        }else{
            savePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
            savePath = savePath.replaceAll("\\\\", "/");    //本地
        }
//        savePath = savePath.replaceAll("/", "\\\\");    //服务器
        try
        {
            if (_log.isInfoEnabled())
            {
                _log.info("开始上传文件");
            }
            String prefix = "";
            String fileName = "";
            String newFileName = "";

            fileName = userFile.getOriginalFilename();
            prefix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            newFileName = System.currentTimeMillis() + PwtzUtils.getRandomNumber(4)+ prefix;
            url = savePath + newFileName;
            BufferedInputStream in = new BufferedInputStream(userFile.getInputStream());
            File file = new File(savePath);
            if  (!file .exists()  && !file .isDirectory())      
            {       
                file .mkdirs();    
            }
//            System.out.println(url);
            FileOutputStream out = new FileOutputStream(new File(url));
            BufferedOutputStream output = new BufferedOutputStream(out);
            Streams.copy(in, output, true);

            List<String[]> list = null;
            if (prefix.endsWith(".xls") || prefix.endsWith(".xlsx"))
            {
                list = ExcelUtil.readExcel(new File(url));
            }
            
            try
            {
                if (list != null && list.size() > 0)
                {
                    totalCount = list.size();
//                    list = removeDuplicate(list);
                    int syzs =list.size();
                    System.out.println(list);
                    for(String[] str:list){
                        if(str.length>2){
                            Map<String, String> map = add(str[0],str[1],str[2]);
                            if(!"0".equals(map.get(ERROR_KEY_OP_RESULT))){
                                String [] newStr = new String[4];
                                newStr[0]= str[0];
                                newStr[1]= str[1];
                                newStr[2]= str[2];
                                newStr[3]= map.get(ERROR_KEY_MSG_DESC);
                                errorlist.add(newStr);
                            }
                        }else{
                            String [] newStr = new String[4];
                            if(str.length>0)
                            newStr[0]= str[0];
                            if(str.length>1)
                            newStr[1]= str[1];
                            newStr[3]= "输入不完整";
                            errorlist.add(newStr);
                        }
                    }
                    if (errorlist != null && errorlist.size() > 0)
                    {
                        eroorCount = errorlist.size();
                    }
                    if (list != null && list.size() > 0)
                    {
                        successCount = syzs - eroorCount;
                    }
                }
            }
            catch (Exception e)
            {
                _log.error(ExceptionUtils.getStackTrace(e));
            }
            if (totalCount > 0 && successCount > 0)
            {
                result = "批量入库成功!";
                msgType = "info";
                opResult = "0";
            }
            else if (totalCount == 0)
            {
                result = "批量入库失败,号码文件为空!";
                msgType = "info";
                opResult = "1";
            }
            else if (totalCount > 0 && successCount == 0)
            {
                result = "批量入库失败,文件号码无效!";
                msgType = "info";
                opResult = "2";
            }

            if (_log.isInfoEnabled())
            {
                _log.info(result);
            }
        }
        catch (IOException e)
        {
            result = "文件上传IO异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (Exception e)
        {
            result = "未知异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
//        return errorlist;
        System.out.println(JsonUtils.bean2json(errorlist));
        writeJsonObject(
                request,
                response,
                "{msgDesc:\"" + result + "\",msgType:\"" + msgType + "\",opResult:\"" + opResult
                        + "\",errorlist:" + JsonUtils.bean2json(errorlist) + ",successCount:\"" + successCount
                        + "\",eroorCount:\"" + eroorCount + "\",totalCount:\"" + totalCount + "\",addr:\""
                        + url.replaceAll("\\\\", "/") + "\"}");
    }

    /**
     * 
     * 向客户端响应json数据 <br/>
     * <p>
     * Description: 向客户端响应json数据 <br/>
     * <p>
     * Author: yangzq<br/>
     * <p>
     * Date: 2013-7-3-下午1:57:18<br/>
     * <p>
     * 
     * @param request
     * @param resp
     * @param jsonData
     * 
     */
    private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
    {
        System.out.println("jsonData="+jsonData);
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try
        {
            pw = resp.getWriter();
            pw.print(jsonData);
            pw.flush();
        }
        catch (IOException e)
        {
            handleException(e);
        }
        finally
        {
            if (null != pw)
            {
                pw.close();
            }
        }
    }
    
    @RequestMapping(value="/list",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<AdminUser> list(int pageSize,int pageNo){
        PaginationList<AdminUser> page=new PaginationList<AdminUser>();
        try
        {
            page=adminUserService.findUser(getUserId(),pageSize, pageNo);
            clearPwd(page.getRecords());
        }
        catch (PwtzDatabaseException e)
        {
        	handleException(e);
        }
        return page;
    }
    
    @RequestMapping(value="/editeuser",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> editeuser(String adminUserId,String mobile,String userName){
        try
        {
        	if(StringUtils.isEmpty(mobile)){
                return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码为空");
            }
            if(!PwtzUtils.isMobile(mobile)){
                return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码错误");
            }
            
            AdminUser bean = adminUserService.load(PwtzUtils.passLong(adminUserId));
            if(bean != null){
            	int count = adminUserService.selectCountByMobile(mobile);
            	if(!mobile.equals(bean.getMobile()) && count>0){
            		return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "手机号已被注册");
            	}
            	
            	bean.setMobile(mobile);
            	bean.setUserName(userName);
            	
            	int row = adminUserService.update(bean);
            	if(row > 0 && bean != null){
            		setLog(1, "修改【"+bean.getLoginName()+"】成功", getUserId());
            		return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "修改用户成功");
            	}
            }
        }
        catch (PwtzDatabaseException e)
        {
        	handleException(e);
        }
        
        return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "修改用户失败");
    }
    
    @RequestMapping(value="/resetpwd",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> resetpwd(String id){
        try
        {
            if(!"admin".equals(getUser().getLoginName())){
            	return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "没有权限操作。");
            }
        	
            AdminUser bean = adminUserService.load(PwtzUtils.passLong(id));
            if(bean != null){
            	String password = PwtzUtils.getRandomNumber(6);
            	bean.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password));
            	int row = adminUserService.update(bean);
            	if(row > 0 && bean != null){
            		setLog(1, "修改【"+bean.getLoginName()+"】成功", getUserId());
            		String smsReturn = sendSmsService.batchSend(bean.getMobile().split(","), "admin将您密码重置为："+password, null, null);
            		if("0".equals(smsReturn) || "1".equals(smsReturn)){
            			AdminSmsSendLog smsSendLog = new AdminSmsSendLog();
            			smsSendLog.setMobile(bean.getMobile());
            			smsSendLog.setContent("密码为："+password);
            			smsSendLog.setOperatorId(getUserId());
            			smsSendLogService.add(smsSendLog);
            		}
            		return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "重置密码成功");
            	}
            }
            
        }
        catch (PwtzDatabaseException e)
        {
        	handleException(e);
        } catch (Exception e)
        {
        	return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "重置密码成功，发送短信失败。");
        }  
        
        return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "重置密码失败");
    }
    
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(String id){
    	try
    	{
    		if(getUserId().equals(id)){
    			return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "不能删除自己"); 
    		}
    		
    		AdminUser bean =  adminUserService.load(PwtzUtils.passLong(id));
    		int row = adminUserService.deleteById(id);
    		if(row > 0 && bean != null){
    			setLog(1, "删除【"+bean.getLoginName()+"】成功", getUserId());
    			return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "删除用户成功");
    		}
    	}
    	catch (PwtzDatabaseException e)
    	{
    		handleException(e);
    	}
    	
    	return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "删除用户失败");
    }
    
    @RequestMapping(value="/load",method=RequestMethod.POST)
    @ResponseBody
    public AdminUser load(String id){
    	try
    	{
    		AdminUser bean =  adminUserService.load(PwtzUtils.passLong(id));
    		clearPwd(bean);
    		return bean;
    	}
    	catch (PwtzDatabaseException e)
    	{
    		handleException(e);
    	}
    	
    	return null;
    }
    
    private AdminUser clearPwd(AdminUser bean){
    	if(bean != null){
    		bean.setLoginPwd(null);
    	}
    	return bean;
    }
    private List<AdminUser> clearPwd(List<AdminUser> list){
    	if(list != null && !list.isEmpty()){
    		for(AdminUser bean : list){
    			clearPwd(bean);
    		}
    	}
    	return list;
    }
}